package com.cyan.app.workflow.promotion;

import android.content.Context;
import android.os.AsyncTask;

import com.cyan.app.workflow.bean.BannerBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.util.Logger;
import com.cyan.app.workflow.util.network.CommHttpListener;
import com.cyan.app.workflow.util.network.VolleyUtil;

import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

public class PromotionTask {
	private static final String TAG = "PromotionTask";

	private List<BannerObjectListener> mBannerListener;
	private BannerUpdateTask mBannerTask;
	private Context context;
	private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public PromotionTask(Context context) {
		mBannerListener = new LinkedList<BannerObjectListener>();
		this.context = context;
	}

	public void registerBannerListener(BannerObjectListener listener) {
		if (listener != null) {
			mBannerListener.add(listener);
		}
	}

	public void unregisterBannerListener(BannerObjectListener listener) {
		if (listener != null) {
			mBannerListener.remove(listener);
		}
	}

	private void notifyBannerListener(BannerBean.Banner banner) {
		for (BannerObjectListener listener : mBannerListener) {
			listener.onUpdate(banner);
		}
	}

	public void startGetBannerObject() {
		if (mBannerTask == null) {
			mBannerTask = new BannerUpdateTask();
		}

		if (mBannerTask.getStatus() == BannerUpdateTask.Status.RUNNING) {
			return;
		}

		if (mBannerTask.getStatus() == BannerUpdateTask.Status.FINISHED) {
			mBannerTask = new BannerUpdateTask();
		}

		mBannerTask.execute();
	}

	public void stopGetBannerObject() {
		if (mBannerTask == null) {
			return;
		}

		if (mBannerTask.getStatus() == BannerUpdateTask.Status.RUNNING) {
			mBannerTask.cancel(false);
		}

		mBannerTask = null;
	}

	public interface BannerObjectListener {
		public void onUpdate(BannerBean.Banner banner);
	}

	public class BannerUpdateTask extends AsyncTask<Integer, Integer, Integer> {
		@Override
		protected Integer doInBackground(Integer... params) {
			getBannerPromotion();
			return 0;
		}
	}

	/**
	 * 获取首页广告图的数据，如果有更新，会通知观察者。
	 */
	private void getBannerPromotion() {
		//VolleyUtil.sendStringRequestByGet(context, "http://client.jiangduoduo.com/action/NewMobileHandler.ashx?UserID=&platformVersion=5.1&platformCode=Android&sign=7910C8297FB44981C91302A6E288433F&appVersion=3.3.0&action=9006&cmdName=app_zz&uuid=000000000000000&cmdId=0&params={}", TAG, null, BannerBean.class, new CommHttpListener<BannerBean>() {
		VolleyUtil.sendStringRequestByGet(context, HttpConfig.HTTP_BANNER_SERVER_URL, TAG, null, BannerBean.class, new CommHttpListener<BannerBean>() {
			@Override
			public void onSuccess(BannerBean bannerBean) {
				super.onSuccess(bannerBean);
				for(BannerBean.Banner banner : bannerBean.getData().getList()) {
					Logger.e(TAG, "banner = " + banner.getImageUrl());
					notifyBannerListener(banner);
				}
			}
		});
	}
	
}
